/*
 *    Copyright 2008-2009 The PoCo Team
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.asemantics.poco.tests;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Provides some utility methods to perform bean comparison.
 *
 * @author Michele Mostarda
 * @version $Id: BeanComparator.java 235 2009-12-19 23:26:56Z simone.tripodi@gmail.com $
 * @see ComparisonReport
 */
public class BeanComparator {

    /**
     * Performs a comparison between two beans, returning a report.
     * The left and right positions are a convention to underline differences.
     *
     * @param left left object
     * @param right right object
     * @return a report of the comparison.
     */
    public static ComparisonReport compareBeans(Object left, Object right) {

        Method[] leftAccessors  = getAccessors(left);
        Method[] rightAccessors = getAccessors(right);

        Map<String,Method> rightAccessorsMap = new HashMap<String,Method>();
        for (Method ra : rightAccessors) {
            rightAccessorsMap.put( ra.getName(), ra );
        }

        ComparisonReport report = new ComparisonReport();

        for (Method la : leftAccessors) {
            try {
                Object leftValue  = la.invoke(left);
                Method rightAccessor = rightAccessorsMap.get( la.getName() );
                if(rightAccessor == null) {
                    throw new RuntimeException(
                            String.format(
                                    "Error in comparison.\nLeft obj: [%s]\nRight obj: [%s].\nCannot find accessor '%s' in right object '%s'",
                                    left.getClass().getName(),
                                    right.getClass().getName(),
                                    la.getName(),
                                    right.toString()
                            )
                    );

                }
                Object rightValue = rightAccessor.invoke(right);
                if (leftValue == null) {
                    if (rightValue != null) {
                        report.addDifference(la, null, rightValue);
                    }
                } else if( ! leftValue.equals(rightValue) ){
                    report.addDifference(la, leftValue, rightValue);
                }
            } catch (Exception e) {
                throw new RuntimeException("Impossible to perform bean comparison", e);
            }
        }

        return report;
    }

    /**
     * Returns a list of bean accessors.
     *
     * @param object object to use to retrieve accessors.
     * @return
     */
    protected static Method[] getAccessors(Object object) {
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo( object.getClass() );
        } catch (Exception e) {
            throw new RuntimeException("Error while extracting accessors.", e);
        }

        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        List<Method> accessors = new ArrayList<Method>();
        for(PropertyDescriptor pd : propertyDescriptors) {
            if( pd.getReadMethod() != null) {
                accessors.add( pd.getReadMethod() );
            }
        }
        return accessors.toArray(new Method[accessors.size()]);
    }

    /**
     * Checks if the given class derives from the interface {@link java.util.List}.
     *
     * @param c class to check.
     * @return <code>true</code> if derives, <code>false</code> otherwise.
     */
    protected boolean isList(Class<?> c) {
        for (Class<?> i : c.getInterfaces()) {
            if (i.equals(List.class)) {
                return true;
            }
        }
        return false;
    }

}
